
import moment from 'moment';
import Link from 'next/link';
import { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import Cookies from 'js-cookie';
import { Popover, Form, Button, Input, Checkbox, message } from 'antd';
import { SelectOutlined, CloseCircleOutlined, PlusCircleOutlined, EditOutlined } from '@ant-design/icons';
import { targetUrl, replaceImageUrl, formatNumTo2, replaceContent, deepClone, totalDays } from '@/utils';
import { validateIDCard } from '@/utils';
// 样式
import styles from '@/styles/ShoppingCart.module.scss';
import ordetStyles from '@/styles/CommonOrder.module.scss';
// api
import { addCustomer } from '@/api/order';
import { getCustomerList, fillContactForm } from '@/store/actions/cart';

// 储存选中游客
function setCustomerToStorage (id, customer){
    const dataList = JSON.parse(sessionStorage.getItem('cartList') || '[]');
    dataList.forEach(item => {
        const { goodsCartActivityListDTO } = item;
        goodsCartActivityListDTO.forEach(dto => {
            if(id === dto.id){
                dto.customersList = customer;
            }
        })
    });
    sessionStorage.setItem('cartList', JSON.stringify(dataList));
}
// 联系人信息
function setContactToStorage (fillContactForm){
    const userInfo = JSON.parse(Cookies.get('userInfo') || "{}"),
          dataList = JSON.parse(sessionStorage.getItem('cartList') || '[]'),
          contact = JSON.parse(sessionStorage.getItem('contact') || '{}');
    const _contact = {};
    dataList.forEach(item => {
        const { goodsCartActivityListDTO } = item;
        goodsCartActivityListDTO.forEach(dto => {
            if(!(contact.name || contact.phoneNum) && dto?.customersList?.length){
                _contact['name'] = dto.customersList[0].name;
                _contact['phoneNum'] = userInfo?.phone;
                sessionStorage.setItem('contact', JSON.stringify(_contact));
                fillContactForm(_contact);
            }
        })
    });
}

// item component
const Item = ({ _getCustomerList, _fillContactForm, data, cart: { customerList } }) => {

    const { id: _id, startDate, endDate, amount, salePrice, orderRules = {} } = data;
    const { realName } = orderRules;
    const isHotel = startDate !== endDate,
          isRealName = realName > 1,
          realNameNum = realName == 2 ? '一名' : '每位';
 
    const [form] = Form.useForm();
    const [updateId, setUpdateId] = useState("");
    const [customers, setCustomers] = useState([]);

    useEffect(() => {
        const _customers = deepClone(customerList);
        setCustomers([..._customers]);
    }, [customerList]);

    //  新增/修改游客信息
    function onAddFormFinish(values) {
        const { contact, idcard, telphone } = values;
        let params = {
            id: updateId,
            idCard: idcard,
            name: contact,
            phoneNum: telphone,
            ticketType: "",
            ticketTypeDesc: "",
        }
        addCustomer(params).then(res => {
            const { code } = res;
            if (code === 0) {
                message.success('操作成功');
                _getCustomerList();
                !updateId && form.resetFields();
            }
        })
    }
    // 修改游客信息，填充form表单
    function updateCustomer(data) {
        const { id = "", name = "", idCard = "", phoneNum = "" } = data;
        form.setFieldsValue({
            contact: name,
            idcard: idCard,
            telphone: phoneNum
        });
        setUpdateId(id)
    }
    // 选择实名游客
    function selectCustomer(data) {
        if (realName === 2) {
            customers.forEach(c => {
                c.checked = false
                if (data.id === c.id) {
                    c.checked = true
                }
            })
        } else if (realName === 3) {
            customers.forEach(c => {
                if (data.id === c.id) {
                    c.checked = customers.filter(item => item.checked).length < amount ? !c.checked : false;
                }
            });
        }
        setCustomers([...customers]);
        setCustomerToStorage(_id, customers.filter(item => item.checked));
        setContactToStorage(_fillContactForm);
    }
    // 删除已选择游客
    function deleteSelectCustomer(id) {
        for (let i = 0, len = customers.length; i < len; i++) {
            const item = customers[i];
            if (item.id === id) {
                item.checked = false;
                break
            }
        }
        setCustomers([...customers]);
        setCustomerToStorage(_id, customers.filter(item => item.checked));
        setContactToStorage(_fillContactForm);
    }

    // Component: 新增游客信息，form表单弹出框
    const popFillForm = (
        <section className={ordetStyles['fill-form']}>
            <h3>添加/修改信息</h3>
            <Form
                form={form}
                onFinish={onAddFormFinish}
                autoComplete="off"
            >
                <Form.Item
                    label="联系人"
                    name="contact"
                    rules={[{ required: true, message: '请输入姓名' }]}
                >
                    <Input placeholder="请输入姓名" />
                </Form.Item>
                <Form.Item
                    label="身份证号"
                    name="idcard"
                    rules={[
                        { required: true, message: '请输入身份证号' },
                        {
                            validator: (rules, value, callback) => {
                                const { status, msg } = validateIDCard(value);
                                !status ? callback(msg) : callback()
                            }
                        }
                    ]}
                >
                    <Input placeholder="请输入身份证号" />
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">确定</Button>
                </Form.Item>
            </Form>
        </section>
    )
    // Component: 选择游客信息
    const popSelectForm = (
        <section className={ordetStyles['fill-select']}>
            <Popover placement="rightTop" trigger="click" content={popFillForm} >
                <button className={ordetStyles['fill-btn']} onClick={() => { updateCustomer({}) }}>
                    <PlusCircleOutlined /> 添加游客
                </button>
            </Popover>
            <h3>选择游客信息</h3>
            {
                customers.length ?
                    customers.map((item) => {
                        return (
                            <dl key={item.id}>
                                <dd onClick={() => { selectCustomer(item) }}>
                                    <Checkbox checked={item.checked} />
                                </dd>
                                <dd>{item.name}</dd>
                                <dd>{item.idCard}</dd>
                                <dd>
                                    <Popover placement="rightTop" trigger="click" content={popFillForm} >
                                        <EditOutlined onClick={() => { updateCustomer(item) }} />
                                    </Popover>
                                </dd>
                            </dl>
                        )
                    }) : <p>暂无游客信息</p>
            }
        </section>
    )
    
    const href = targetUrl(data);

    return (
        <div className={styles['tr']}>
            <div className={styles['product']}>
                <Link href={href}>
                    <a target="_blank">
                        <img src={replaceImageUrl(data.img)} alt="" />
                    </a>
                </Link>
                <div className={styles['product-info']}>
                    <Link href={href}><a target="_blank">{data.goodsName}</a></Link>
                    <p>
                        <span>{data.goodsExtendName}</span>
                    </p>
                </div>
            </div>
            <div className={styles['info']}>
                {
                    isHotel 
                    ? <>
                        <p className={styles['date']}>入住：<span>{startDate} (<i>{moment(startDate).format('dddd')}</i>)</span></p>
                        <p className={styles['date']}>退房：<span>{endDate} (<i>{moment(endDate).format('dddd')}</i>)</span></p>
                    </>
                    : <p>使用日期：<span>{startDate}</span></p>
                }
                <p className={styles['num']}>
                    {
                        data.projectId == 3 
                        ? <>
                            <span>￥<em>{salePrice}</em></span> x <em>{totalDays(data.startDate,data.endDate)}</em> x <em>{amount}</em>
                        </>
                        : <>
                            <span>￥<em>{salePrice}</em></span> x <em>{amount}</em>
                        </>
                    }
                </p>
                <p className={styles['total']}>
                    小计：<span>￥<em>{
                        data.projectId == 3 
                        ? formatNumTo2(amount*salePrice*totalDays(data.startDate,data.endDate))
                        : formatNumTo2(amount*salePrice)
                    }</em></span>
                </p>
            </div>
            <div className={[styles['detail'], isRealName && styles['detail-tourist']].join(' ')}>
                <div className={styles['tips']}>
                    <h5>购买须知：</h5>
                    <p dangerouslySetInnerHTML={{__html: replaceContent(data.predefinedInstructions)}}></p>
                </div>
                {
                    isRealName && <div className={styles['tourist']}>
                                    <p className={styles['t-tips']}>注：该订单需要<em>{realNameNum}</em>游客提供实名信息</p>
                                    <div className={styles['t-tourist']}>
                                        <Popover placement="topLeft" trigger="click" content={popSelectForm}>
                                            <button className={[ordetStyles['fill-btn'], ordetStyles['small']].join(' ')}>
                                                <SelectOutlined /> 选择游客
                                            </button>
                                        </Popover>
                                        <div className={styles['thead']}>
                                            <div>游客姓名</div>
                                            <div>身份证号</div>
                                            <div>操作</div>
                                        </div>
                                        <div className={styles['tbody']}>
                                            {
                                                !customers.filter(item => item.checked).length ? <p>未选择游客信息</p> : ""
                                            }
                                            {
                                                customers.map((item) => {
                                                    if (item.checked) {
                                                        return (
                                                            <dl key={item.id}>
                                                                <dd>{item.name}</dd>
                                                                <dd>{item.idCard}</dd>
                                                                <dd><CloseCircleOutlined onClick={() => { deleteSelectCustomer(item.id) }} /></dd>
                                                            </dl>
                                                        )
                                                    }
                                                    return null
                                                })
                                            }
                                        </div>
                                    </div>
                                </div>
                }
            </div>
        </div>
    )
}

const mapStateToProps = state => {
    return {
        cart: state.cart
    }
}
const mapDispatchToProps = dispatch => {
    return {
        _getCustomerList: v => dispatch(getCustomerList(v)),
        _fillContactForm: v => dispatch(fillContactForm(v))
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Item);